package com.example.imageprocessing.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.example.imageprocessing.R;
import com.example.imageprocessing.util.RealPathFromUriUtils;
import com.example.imageprocessing.view.DragImageView;
import com.melnykov.fab.FloatingActionButton;
import com.tiancaicc.springfloatingactionmenu.MenuItemView;
import com.tiancaicc.springfloatingactionmenu.OnMenuActionListener;
import com.tiancaicc.springfloatingactionmenu.SpringFloatingActionMenu;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Uri imageUri;

    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    public static final int TIAOSE = 3;

    private DragImageView picture;

    private SpringFloatingActionMenu springFloatingActionMenu;

    String[] mPermissionList = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    public static int REQUEST_CODE;

    public static final int REQUEST_CODE_PINTU = 1002;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        picture = findViewById(R.id.picture);

        final FloatingActionButton fab = new FloatingActionButton(this);
        fab.setType(FloatingActionButton.TYPE_NORMAL);
        fab.setImageResource(R.drawable.add);
        fab.setColorPressedResId(R.color.colorPrimary);
        fab.setColorNormalResId(R.color.fab);
        fab.setColorRippleResId(R.color.text_color);
        fab.setShadow(true);

        springFloatingActionMenu = new SpringFloatingActionMenu.Builder(this)
                .fab(fab)
                //add menu item via addMenuItem(bgColor,icon,label,label color,onClickListener)
                //添加菜单按钮参数依次是背景颜色,图标,标签,标签的颜色,点击事件
                .addMenuItem(R.color.photo, R.mipmap.photo, "拍照", R.color.text_color, this)
                .addMenuItem(R.color.chat, R.mipmap.album, "相册", R.color.text_color, this)
                .addMenuItem(R.color.quote, R.mipmap.color, "调色", R.color.text_color, this)
                .addMenuItem(R.color.link, R.mipmap.watermark, "水印", R.color.text_color, this)
                .addMenuItem(R.color.audio, R.mipmap.matrix, "矩阵", R.color.text_color, this)
                .addMenuItem(R.color.text, R.mipmap.special_effects, "效果", R.color.text_color, this)
                .addMenuItem(R.color.video, R.mipmap.puzzle, "拼图", R.color.text_color, this)
                //you can choose menu layout animation
                //设置动画类型
                .animationType(SpringFloatingActionMenu.ANIMATION_TYPE_TUMBLR)
                //setup reveal color while the menu opening
                //设置reveal效果的颜色
                .revealColor(R.color.colorPrimary)
                //set FAB location, only support bottom center and bottom right
                //设置FAB的位置,只支持底部居中和右下角的位置
                .gravity(Gravity.RIGHT | Gravity.BOTTOM)
                .onMenuActionListner(new OnMenuActionListener() {
                    @Override
                    public void onMenuOpen() {
                        //set FAB icon when the menu opened
                        //设置FAB的icon当菜单打开的时候
                        fab.setImageResource(R.drawable.close);
                    }

                    @Override
                    public void onMenuClose() {
                        //set back FAB icon when the menu closed
                        //设置回FAB的图标当菜单关闭的时候
                        fab.setImageResource(R.drawable.add);
                    }
                })
                .build();

    }

    @Override
    public void onClick(View view) {
        MenuItemView menuItemView = (MenuItemView) view;
        Toast.makeText(this, menuItemView.getLabelTextView().getText(), Toast.LENGTH_SHORT).show();

        switch (menuItemView.getLabelTextView().getText().toString()) {
            case "拍照":
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                        1001);
                springFloatingActionMenu.hideMenu();
                break;

            case "相册":
                ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
                REQUEST_CODE = 100;
                springFloatingActionMenu.hideMenu();
                break;

            case "调色":
                ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
                REQUEST_CODE = 101;
                springFloatingActionMenu.hideMenu();
                break;

            case "水印":
                ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
                REQUEST_CODE = 102;
                springFloatingActionMenu.hideMenu();
                break;
            case "矩阵":
                ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
                REQUEST_CODE = 103;
                springFloatingActionMenu.hideMenu();
                break;
            case "效果":
                ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
                REQUEST_CODE = 104;
                springFloatingActionMenu.hideMenu();
                break;
            case "拼图":
                ImageConfig imageConfig
                        = new ImageConfig.Builder(MainActivity.this, new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.yancy_blue200))
                        .titleBgColor(getResources().getColor(R.color.yancy_blue200))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）
                        .mutiSelect()
                        // 多选时的最大数量   （默认 3 张）
                        .mutiSelectMaxSize(9)
                        // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                        .filePath("/ImageSelector/Pictures")
                        .build();

                // 开启图片选择器
                ImageSelector.open(imageConfig);
                springFloatingActionMenu.hideMenu();
                break;
        }
    }

    /**
     * 启动相机程序
     */
    private void openCamera() {
        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(MainActivity.this,
                    "com.example.image.fileprovider", outputImage);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 100:
                if (resultCode == RESULT_OK) {
                    String imagePath = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                    picture.setImageBitmap(bitmap);
                }
                break;
            case 101:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        Intent intent = new Intent(MainActivity.this, PrimaryColorActivity.class);
                        intent.putExtra("imgUrl", realPathFromUri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
                    }

                    break;
                }

            case 102:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        Intent intent = new Intent(MainActivity.this, AddWatermarkActivity.class);
                        intent.putExtra("imgUrl", realPathFromUri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case 103:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        Intent intent = new Intent(MainActivity.this, ColorMatrixActivity.class);
                        intent.putExtra("imgUrl", realPathFromUri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case 104:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        Intent intent = new Intent(MainActivity.this, TuPianXiaoGuo.class);
                        intent.putExtra("imgUrl", realPathFromUri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case REQUEST_CODE_PINTU:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                    Intent intent = new Intent(MainActivity.this, PinTuActivity.class);
                    intent.putStringArrayListExtra("imgUrlList", pathList);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
                    getImage(REQUEST_CODE);
                } else {
                    Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
                }

                break;
            case 1001:
                boolean writeES = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readES = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                boolean cameraES = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                if (grantResults.length > 0 && writeES && readES && cameraES) {
                    openCamera();
                } else {
                    Toast.makeText(this, "请设置相机权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void getImage(int requestCode) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    requestCode);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, requestCode);
        }
    }

}